package com.haoshuang.zhouzhoubang.model.http

import com.blankj.utilcode.util.ActivityUtils
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.jeremyliao.liveeventbus.LiveEventBus
import com.haoshuang.zhouzhoubang.model.event.LogoutEvent
import com.haoshuang.zhouzhoubang.ui.page.account.login.LoginActivity
import com.lnkj.jialubao.utils.AccountUtils
import com.mufeng.libs.config.HttpConfig
import com.mufeng.libs.net.interceptor.CacheInterceptor
import com.mufeng.libs.net.interceptor.logging.LogInterceptor
import com.mufeng.libs.utils.startPage
import okhttp3.OkHttpClient

class HttpConfigImpl : HttpConfig {
    override val baseUrl: String
        get() = URLConstants.baseUrl

    override val code: ArrayList<String>
        get() = arrayListOf("code")
    override val msg: ArrayList<String>
        get() = arrayListOf("msg")
    override val data: String
        get() = "data"
    override val successCode: IntArray
        get() = intArrayOf(1, 200)
    override val errorCode: IntArray
        get() = intArrayOf(0, 400)

    override fun httpCommonParams(): Map<String, Any> {
        val params = mutableMapOf<String, Any>()
        val token = AccountUtils.token
        if (token.isNotEmpty()) {
            params["token"] = token
            params["team_id"] = AccountUtils.user?.team_id.toString()
        }
        params["is_team"] = 1
        return params
    }

    override fun httpRequestHeader(): Map<String, String> {
        val handlers = mutableMapOf<String, String>()
        val token = AccountUtils.token
        if (token.isNotEmpty()) {
            handlers["token"] = token
        }
        return handlers
    }

    override fun handlerNetworkError(code: Int) {
        when (code) {
            ErrorCode.TOKEN_ERROR, ErrorCode.TOKEN_AUTH_ERROR -> {
                //登录超时 退出到登录
                if (AccountUtils.isTokenErrorJumpLoginPage) {
                    AccountUtils.isTokenErrorJumpLoginPage = false
                    ActivityUtils.getTopActivity().startPage<LoginActivity>()
                    ActivityUtils.finishOtherActivities(LoginActivity::class.java)
                    AccountUtils.logout()
                    LiveEventBus.get(LogoutEvent::class.java).post(LogoutEvent)
                }
            }
        }
    }

    override fun initHttpInterceptor(builder: OkHttpClient.Builder) {
        builder
            .addInterceptor(NetworkStatusInterceptor())
            .addInterceptor(CacheInterceptor())
            .addInterceptor(LogInterceptor())
    }
}